package com.zmq.utils.meil;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;
import java.util.Random;

public class SendEmail implements MailConfig {

    public static void main(String[] args) throws Exception {
        Random i = new Random();
        int x = i.nextInt();
        String str = "1325";
        /**收件人邮箱*/
        String[] toMail = {"1773323111@qq.com","625648624@qq.com","2054503375@qq.com"};
        /**邮件标题*/
        String mailTitle  = "验证码";
        /**邮件内容，支持HTML*/
        String mailContent = "您的验证码是<font size=\"4\" color=\"red\">\n"+ str +"</font>";


        toMails(toMail,mailTitle,mailContent);

        System.out.println("验证码是："+str);
    }
    public static boolean toMails (String[] toMail,String mailTitle,String mailContent)  {

        Properties properties = new Properties();
        properties.put("mail.transport.protocol", PROTOCOL);// 连接协议
        properties.put("mail.smtp.host", HOST);// 主机名
        properties.put("mail.smtp.port", PORT);// 端口号
        properties.put("mail.smtp.auth", "true");
        properties.put("mail.smtp.ssl.enable", SSL);// 设置是否使用ssl安全连接 ---一般都使用
        properties.put("mail.debug", "true");// 设置是否显示debug信息 true 会在控制台显示相关信息
        try{


        // 得到回话对象
        Session session = Session.getInstance(properties);
        // 获取邮件对象
        Message message = new MimeMessage(session);
        // 设置发件人邮箱地址
        message.setFrom(new InternetAddress(FORM_MAIL));
        // 设置收件人邮箱地址
        String toMailList = getMailList(toMail);
        InternetAddress[] iaToMailList = new InternetAddress().parse(toMailList);
        message.setRecipients(Message.RecipientType.TO,iaToMailList);

        // 设置邮件标题
        message.setSubject(mailTitle);
        // 设置邮件内容
        //message.setText(mailContent);
        message.setContent(mailContent, "text/html;charset=UTF-8");
        // 得到邮差对象
        Transport transport = session.getTransport();
        // 连接自己的邮箱账户
        transport.connect(FORM_MAIL, AUTHORIZATION);// 密码为QQ邮箱开通的stmp服务后得到的客户端授权码
        // 发送邮件
        transport.sendMessage(message, message.getAllRecipients());
        transport.close();
        }catch (Exception e){
            return false;
        }
        return true;
    }


    //获取收件人地址列表
    public static String getMailList(String[] mailArray){
        StringBuffer toList = new StringBuffer();
        int length = mailArray.length;
        if(mailArray!=null && length <2){
            toList.append(mailArray[0]);
        }else{
            for(int i=0;i<length;i++){
                toList.append(mailArray[i]);
                if(i!=(length-1)){
                    toList.append(",");
                }
            }
        }
        return toList.toString();
    }
}
